using System;
using System.Collections.Generic;

namespace Octubre.Framework
{
	public static class Database
	{
		public static TEntity Load<TEntity>(Guid Id)
			where TEntity : Storable, new()
		{
			return (TEntity)saved[ new saveitem {
				Type = typeof(TEntity),
				Id = Id }];
		}

		public static TEntity Load<TEntity, TRecord> ()
			where TEntity : Storable, new()
			where TRecord : Record<TEntity>
		{
			if (Initialized) {
				return Load<TEntity> (StaticEntities [typeof(TRecord)].Id);
			} else {
				return (TEntity) StaticEntities[typeof(TRecord)];
			}
		}

		public static TEntity Load<TEntity>(string Id)
			where TEntity : Storable, new()
		{
			return Load<TEntity>(Guid.Parse(Id));
		}

		internal static Dictionary<Type,Storable> StaticEntities
			= new Dictionary<Type, Storable>();

		public static void Save (params Storable[] entities)
		{
			foreach (var entity in entities) {
				saved.Add(new saveitem {
					Type = entity.GetType(),
					Id = entity.Id
				}, entity);
			}
		}

		internal static bool Initialized = false;

		private static Dictionary<saveitem, Storable> saved =
			new Dictionary<saveitem, Storable>();

		private struct saveitem
		{
			public Type Type;
			public Guid Id;
		}

	}
}